package transformers;

import java.util.ArrayList;

import utils.AmbigousPath;
import utils.Node;
import utils.Path;
import utils.TreeUtils;
import exceptions.AmbiguityException;

public class ContextTransformer {
	public Node configuration;
	
	public ContextTransformer(Node configuration) {
		this.configuration = configuration;
	}
	
/*	public boolean valid(Node rule)
	{
		// validate cell names => check if they are defined in the configuration
		//boolean validNames = TreeUtils.validateCellNames(rule, configuration);
		
		// cell name is not child of other name in the configuration
		//boolean validParentRelation = TreeUtils.validateParentRelation(rule, configuration);
	}
*/	
	/**
	 * Computes the context for a given rule
	 * Throws AmbiguityException if there is an ambiguity or more
	 * @param rule
	 * @return
	 * @throws AmbiguityException
	 */
	public Node getContext(Node rule) throws AmbiguityException

	{
		ArrayList<AmbigousPath> ambigousPaths = null;
		ArrayList<Path> pathContexts = null;
		
		if (rule.children.size() == 0)
		{
			ArrayList<Node> list= TreeUtils.searchByLabel(configuration, rule.label);
			if (list.size() > 1)
				ambigousPaths = TreeUtils.detectAmbiguityForList(list, configuration);
			else if (list.size() == 1) 
				return (new Path(configuration, list.get(0), rule)).getPath().root;
		}
		else
		{
			ArrayList<Node> leaves = TreeUtils.getLeaves(rule);
			ArrayList<Node> intermediateNodes = TreeUtils.getIntermediateNodes(rule);
			ArrayList<Path> leavesPaths = TreeUtils.getPaths(configuration, leaves);
			ArrayList<Path> intermediatePaths = TreeUtils.getPaths(configuration, intermediateNodes);
			pathContexts = TreeUtils.getPathContext(leavesPaths, intermediatePaths, rule.label);
			ambigousPaths = TreeUtils.detectAmbiguity(pathContexts);
		}
		
		if (ambigousPaths == null)
			{
				Node context = TreeUtils.merge(pathContexts);
//				TreeUtils.printTree(context, "");
				return context;
			}
		else 
		{
			throw new AmbiguityException(ambigousPaths);
		}
	}
}
